package ai.mspbots.common.web;

import co.elastic.apm.api.ElasticApm;
import co.elastic.apm.api.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class HeaderFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(HeaderFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader("trace.id");
        logger.info("trace.id: {}", header);
        Transaction transaction = ElasticApm.currentTransaction();
        if (StringUtils.hasText(header)) {
            transaction.getTraceId();
        }

        filterChain.doFilter(request, response);
    }
}
